package com.changgou.oauth.util;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;

/*****
 * @Author: 黑马训练营
 * @Description: com.changgou.oauth.util
 ****/
public class JwtToken {


    /***
     * 颁发管理员令牌
     * @return
     */
    public static String adminJwt(){
        //读取证书
        ClassPathResource resource = new ClassPathResource("changgoubj.jks");

        //获取私钥
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource,"changgoubj".toCharArray());
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("changgoubj", "changgoubj".toCharArray());//证书中的公私钥
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();

        //定义载荷
        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("roles","admin");//指定令牌中用户的角色

        /***
         * 生成令牌
         *  1:载荷数据
         *  2:秘钥数据
         */
        Jwt jwt = JwtHelper.encode(JSON.toJSONString(dataMap), new RsaSigner(rsaPrivateKey));

        //获取令牌
        String token = jwt.getEncoded();
        return token;
    }
}
